<template>
  <div class="main">
    <mine-title>我的项目</mine-title>
    <div class="content">
      <div class="block-header">
        <div class="block-header-left">
          <mine-button type="primary" @click="addProFn()"><i class="iconfont icon-add-line"></i>新建项目</mine-button>
          <mine-button type="primary" secondary @click="loadData()"><i class="iconfont icon-reset-line"></i>刷新</mine-button>
          <mine-button @click="delDataFn()" secondary :disabled="!multipleSelection.length"><i class="iconfont icon-delete-line"></i>删除</mine-button>
        </div>
        <div class="block-header-right"></div>
      </div>
      <el-form ref="form" :inline="true" :model="listQuery" class="demo-form-inline">
        <el-row :gutter="2">
          <el-col :xs="12" :sm="8" :md="8" :lg="3">
            <el-form-item label="">
              <el-input
                v-model="listQuery.id"
                placeholder="项目编号"
                size="small"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :md="8" :lg="3">
            <el-form-item label="">
              <el-input
                v-model="listQuery.projectName"
                placeholder="项目名称"
                size="small"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :md="8" :lg="3">
            <el-form-item label="">
              <el-input
                v-model="listQuery.projectDesc"
                placeholder="项目描述"
                size="small"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :md="8" :lg="4">
            <el-form-item label="">
              <el-select
                v-model="listQuery.rates"
                placeholder="项目进度"
                multiple
                collapse-tags
                size="small"
              >
                <el-option
                  v-for="item in ratesList"
                  :key="item.value"
                  :label="item.text"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :md="8" :lg="3">
            <el-form-item label="">
              <el-input
                v-model="listQuery.materialSetName"
                placeholder="关联数据集"
                size="small"
              />
            </el-form-item>
          </el-col>

          <el-col :xs="12" :sm="8" :md="8" :lg="4">
            <el-form-item label="">
              <el-select
                v-model="listQuery.types"
                placeholder="项目类型"
                multiple
                collapse-tags
                size="small"
              >
                <el-option
                  v-for="item in classifies"
                  :key="item.name"
                  :label="item.text"
                  :value="item.name"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="8" :md="8" :lg="4">
            <el-form-item label="">
              <el-select
                v-model="listQuery.modelArithmetics"
                placeholder="使用模型"
                multiple
                collapse-tags
                size="small"
              >
                <el-option
                  v-for="item in modelArithmetics"
                  :key="item.value"
                  :label="item.text"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table
        :data="tableData"
        style="width: 100%"
        :max-height="tableHeight"
        @selection-change="handleSelectionChange"
        ref="multipleTable"
        v-loading="loading">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="id" label="项目编号" width="100" show-overflow-tooltip></el-table-column>
        <el-table-column prop="projectName" label="项目名称" width="100" show-overflow-tooltip />
        <el-table-column prop="projectDesc" label="项目描述" width="100" show-overflow-tooltip />
        <el-table-column prop="progressRate" label="项目进度" width="100" :formatter="rateFormat">
          <template slot-scope="scope">
            <!-- 无监督学习-训练完成状态不点击 -->
            <div v-if="
            scope.row.projectType === 'data_unsupervised' &&
            isPublish(scope.row)
            " style="font-size: 12px">{{ rateFormat(scope.row, scope.column, scope.row.progressRate) }}</div>
            <el-button v-else @click="gotoResult(scope.row, false)" type="text" size="mini">{{ rateFormat(scope.row, scope.column, scope.row.progressRate) }}</el-button></template>
        </el-table-column>
        <el-table-column prop="materialSetName" label="关联数据集" width="100" show-overflow-tooltip />
        <el-table-column prop="projectType" label="项目类型" width="100" show-overflow-tooltip :formatter="classifyFormat" />
        <el-table-column prop="arithmetic" label="使用模型" width="100" show-overflow-tooltip />
        <el-table-column label="模型效果" width="80" align="center">
          <template slot-scope="scope">
            <!-- 无监督学习没有查看详情 -->
            <div v-if="scope.row.projectType !== 'data_unsupervised'">
              <el-button v-show="isPublish(scope.row) || isPublished(scope.row)" @click="gotoResult(scope.row, false)" type="text" size="mini">查看详情</el-button></div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" min-width="130px">
          <template slot-scope="scope">
            <!-- 无监督学习只有下载功能 -->
            <div v-if="scope.row.projectType === 'data_unsupervised'">
              <el-button @click="downloadUnFile(scope.row)" type="text" size="mini" v-show="isPublish(scope.row)">下载</el-button>
              <el-button @click="openModel(scope.row)" type="text" size="mini" v-show="statusUnpublish(scope.row) && isPublish(scope.row)">训练情况</el-button></div>
            <div v-else>
              <el-button @click="gotoDetial(scope.row)" type="text" size="mini" v-show="isPublished(scope.row)">下载</el-button>
              <el-button @click="gotoTest(scope.row)" type="text" size="mini" v-show="isPublished(scope.row)">测试</el-button>
              <el-button @click="gotoDetial(scope.row)" type="text" size="mini" v-show="isPublished(scope.row)">下线</el-button>
              <el-button @click="gotoPublish(scope.row)" type="text" size="mini" v-show="statusUnpublish(scope.row) && isPublish(scope.row)">发布</el-button>
              <el-button @click="openModel(scope.row)" type="text" size="mini" v-show="statusUnpublish(scope.row) && isPublish(scope.row)">训练情况</el-button></div>
          </template>
        </el-table-column>
      </el-table>
      <mine-pagination
        @numberChange="numberChange"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage">
      </mine-pagination>
    </div>
  </div>
</template>

<script>
import request from '@/modules/index/utils/request';
import { classifyList, progressRate } from '@/utils/common';
import qs from 'qs';
import _ from 'lodash';
const rate = progressRate;

export default {
  data() {
    return {
      listQuery: {
        id: '',
        projectName: '',
        projectDesc: '',
        rates: [],
        materialSetName: '',
        types: [],
        modelArithmetics: [],
      },
      total: 100,
      pageSize: 10,
      currentPage: 1, //table当前页数
      // tableHeight: '100%', //table可显示区域高度
      tableHeight: '300px',
      tableData: [],
      multipleSelection: [],
      modelArithmetyList: [],
      loading: false,
    };
  },
  mounted() {
    this.loadData();
    this.loadModelArithmetyList();
  },
  methods: {
    // 无监督学习-下载
    async downloadUnFile(row) {
      try {
        this.$store.dispatch('proAdminProjectIdGetResultFile', {
          id: row.id,
        });
      } catch (e) {
        console.error(e);
      }
    },
    gotoDetial(row) {
      // console.log("查看详情:" + row.id);
      this.$router.push({
        path: '/prolist/prodetail',
        query: { id: row.id },
      });
    },
    gotoTest(row) {
      this.$router.push({
        path: '/prolist/protest',
        query: { id: row.id, type: row.projectType },
      });
    },
    gotoResult(row, isToModelResult) {
      if (row.progressRate === 'material') {
        this.$router.push({
          name: 'proEdit',
          params: { data: row, isToModelResult: isToModelResult },
        });
      }
      if (row.progressRate === 'train') {
        //  this.$router.push({
        //   name:"proEdit",
        //   params: {data:row,isToModelResult:isToModelResult}
        // });
        return;
      }
      if (row.progressRate === 'publish' || isToModelResult) {
        this.$router.push({
          name: 'proEdit',
          params: { data: row, isToModelResult: true },
        });
      }
      if (row.progressRate === 'published') {
        this.$router.push({
          path: '/prolist/prodetail',
          query: { id: row.id },
        });
      }
      return;
    },
    gotoPublish(row) {
      // console.log("模型发布:" + row.id);
      this.$router.push({
        name: 'proEdit',
        params: { data: row, isToModelResult: true },
      });
    },
    async openModel(row) {
      let msg = '';
      try {
        msg = await this.loadTrainMsgById(row.id);
      } catch (err) {
        msg = '请联系开发人员了解原因！';
      }
      this.$alert(msg, '训练消息', {
        confirmButtonText: '确定',
      });
    },
    loadTrainMsgById(id) {
      return new Promise((resolve, reject) => {
        request({
          url: '/traininginfo/training-info/getByProjectId', //接口
          method: 'get',
          params: {
            projectId: id,
          },
        })
          .then((res) => {
            if (res.data.success) {
              if (res.data.data.errorInformation) {
                let info = JSON.parse(res.data.data.errorInformation);
                resolve(info.msg);
              } else {
                resolve('无返回原因！');
              }
            } else {
              this.$message.error('获取失败！');
              reject(res.data.msg);
            }
          })
          .catch((err) => {
            reject(err.response.data);
          });
      });
    },
    loadModelArithmetyList() {
      let _this = this;
      request({
        url: '/project/get-algorithm-name', //接口
        method: 'get',
      })
        .then((res) => {
          if (res.data.success) {
            if (res.data.data) {
              let dataList = res.data.data;
              _this.modelArithmetyList = dataList.map((item) => {
                return { value: item, text: item };
              });
            } else {
              _this.modelArithmetyList = [];
            }
          } else {
            this.$message.error('获取失败！');
          }
        })
        .catch((err) => {
          this.$message.error(err.response.data);
        });
    },
    addProFn() {
      // this.$router.push("/prolist/proedit");
      this.$router.push({
        name: 'proEdit',
        params: { id: null },
      });
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.loadData();
    },
    //查询
    onSubmit() {
      this.currentPage = 1;
      this.loadData();
    },
    delDataFn() {
      this.$mineConfirm('确认要删除这个项目', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        const ids = this.multipleSelection.map((item) => item.id);
        request({
          url: '/project/batch', //接口
          method: 'delete',
          params: {
            idList: ids,
          },
          paramsSerializer: (params) => {
            return qs.stringify(params, { indices: false });
          },
        }).then((response) => {
          let result = response.data;
          if (!result.success) {
            this.$message.error('删除失败');
            return;
          }
          this.$message.success('删除成功');
          this.handleCurrentChange(1);
        });
      }).catch(() => {});
    },

    handleSelectionChange(val) {
      // eslint-disable-next-line no-debugger
      this.multipleSelection = val;
    },
    loadData() {
      const { currentPage, listQuery } = this;
      const {
        id,
        projectName,
        projectDesc,
        rates,
        materialSetName,
        types,
        modelArithmetics,
      } = listQuery;
      let data = qs.parse({
        page: currentPage,
        pageSize: 10,
        id: id,
        projectName: projectName,
        projectDesc: projectDesc,
        rates: rates,
        materialSetName: materialSetName,
        types: types,
        modelArithmetics: modelArithmetics,
      });
      this.loading = true;
      request({
        url: '/project/search-page', //接口
        method: 'post',
        data: data,
      }).then((response) => {
        let result = response.data;
        if (!result.success) {
          return;
        }
        let data = result.data;
        this.tableData = data.list;
        this.total = data.rowCount;
        this.loading = false;
      });
    },
    rateFormat(row, column, cellValue, index) {
      let result = _.find(rate, { value: cellValue })
        ? _.find(rate, { value: cellValue }).text
        : '';
      return result;
    },
    classifyFormat(row, column, cellValue, index) {
      let result = _.find(classifyList, { name: cellValue })
        ? _.find(classifyList, { name: cellValue }).text
        : '';
      return result;
    },
    refreshData() {
      this.loadData();
    },
    reSetData() {
      this.listQuery = {
        id: '',
        projectName: '',
        projectDesc: '',
        rates: [],
        materialSetName: '',
        types: [],
        modelArithmetics: [],
      };
      this.page = 1;
      this.refreshData();
    },
    isMaterial(row) {
      return row.progressRate === 'material';
    },
    isTrain(row) {
      let result = true;
      if (row.progressRate !== 'train') {
        result = false;
      }
      return result;
    },
    isPublish(row) {
      let result = true;
      if (row.progressRate !== 'publish') {
        result = false;
      }
      return result;
    },
    isPublished(row) {
      let result = true;
      if (row.progressRate !== 'published') {
        result = false;
      }
      return result;
    },
    statusPublished(row) {
      return row.status === 'published';
    },
    statusUnpublish(row) {
      return row.status === 'unpublish';
    },
    statusError(row) {
      return row.status === 'error';
    },
    clear () {
      this.$refs.form.resetFields();
      this.loadData(true);
    },
    numberChange (val) {
      switch (val.flag) {
        case 'pageSize':
          this.pageSize = val.pageSize;
          this.loadData(true);
          break;
        case 'currentPage':
          this.currentPage = val.currentPage;
          this.loadData(false);
          break;
        default:
          break;
      }
    },
  },
  computed: {
    ratesList: function () {
      return rate;
    },
    classifies: function () {
      return classifyList;
    },
    modelArithmetics: function () {
      return this.modelArithmetyList;
    },
  },
};
</script>
<style scoped lang="less">
.demo-form-inline {
  margin-bottom: 22px;
  .el-form-item {
    margin-bottom: 0;
  }
  .el-date-editor.el-input,
  .el-date-editor.el-input__inner {
    width: 100%;
  }
}
</style>
